#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server = new QTcpServer;
    server->listen(QHostAddress::Any,1111);//等待连接
    connect(server,SIGNAL(newConnection()),this,SLOT(new_connect()));
    ui->pushButton_3->setEnabled(false);

}

MainWindow::~MainWindow()
{
    delete ui;
}

//找到与服务器链接的客户端
void MainWindow::new_connect()
{

    socket = server->nextPendingConnection();
    soc.push_back(socket);
    connect(socket,SIGNAL(readyRead()),this,SLOT(ready_read()));

}


void MainWindow::ready_read()
{
    char buf[255] = {};
    for(unsigned int i=0; i<soc.size(); i++)
    {
        if(soc[i]->read(buf,sizeof(buf)))
        {
            QFile file("/home/zhizhen/msg.txt");
            if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append))
            {
                qDebug("Open failed");
                exit(0);
            }
            QString buf1;
            buf1 = buf;
            buf1.toStdString().c_str();
            QTextStream txtOutput(&file);
            txtOutput << buf1 << endl;
            file.close();
            for(unsigned int i=0; i<soc.size(); i++)
            {
//                ui->read_listWidget->addItem(buf);
                soc[i]->write(buf,sizeof(buf));
            }
        }
    }
}


void MainWindow::on_pushButton_clicked()
{
 //   socket->write(ui->lineEdit->text().toStdString().c_str(),ui->lineEdit->text().length());
  //  ui->read_listWidget->addItem("server:"+ui->lineEdit->text());
  //  ui->lineEdit->setText("");
}

void MainWindow::on_pushButton_2_clicked()
{
    QFile file("/home/zhizhen/msg.txt");
    file.open(QFile::WriteOnly | QFile::Truncate);
    file.close();

}

void MainWindow::on_hide_btn_clicked()
{
    char buf[255] = "*1*2+3=4-9(!@#$)!@#$%^&*()_+";
    for(unsigned int i=0; i<soc.size(); i++)
    {
        soc[i]->write(buf,sizeof(buf));
    }
        ui->hide_btn->setEnabled(false);
        ui->pushButton_3->setEnabled(true);
}

void MainWindow::on_pushButton_3_clicked()
{
    char buf[255] = "*1*2+3=4-9(!@#$$$$$)!@#$%^&*()_+";
    for(unsigned int i=0; i<soc.size(); i++)
    {
        soc[i]->write(buf,sizeof(buf));
    }
    ui->pushButton_3->setEnabled(false);
    ui->hide_btn->setEnabled(true);
}
